<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hyperf_mall
 * @contact  hyperf_mall@163.com
 */

namespace App\Repository;

use App\Constants\Category;
use App\Model\ArticleCategoryModel;
use Hyperf\Di\Annotation\Inject;

class ArticleCategoryRepository extends BaseRepository
{
    /**
     * @Inject
     * @var ArticleCategoryModel
     */
    protected $model;


    /**
     * Notes: 获取分类树
     * Author: Bruce.z
     * DateTime: 2021/12/29 10:16
     * @param int $depth 1|2|3
     * @return array
     */
    public function getTree($depth = Category::CATE_THREE) : array
    {
        if($depth == Category::CATE_TWO){
            return $this->nextTree(0);
        }else{
            $level = $this->_searchFactor(['pid'=>0])->get(['pid','title','id','sort','create_time','status'])->toArray();
            if($depth == Category::CATE_FIRST) return $level;

            foreach ($level as &$item){
                $item['children'] = $this->nextTree($item['id']);
            }

            return $level;
        }
    }

    private function nextTree($pid)
    {
        $rows = $this->_searchFactor(['pid'=>$pid])->get(['pid','title','id','sort','create_time','status'])->toArray();
        if(empty($rows)) return [];

        $ids = array_column($rows, 'id');
        $level_next = $this->_searchFactor(['pid'=>$ids])->get(['pid','title','id','sort','create_time','status'])->toArray();

        foreach ($rows as &$v){
            foreach ($level_next as $value){
                if($v['id'] == $value['pid']){
                    $v['children'][] = $value;
                }
            }
        }

        return $rows;
    }

    /**
     * Notes:
     * Author: Bruce.z
     * DateTime: 2021/12/29 10:50
     * @param int $depth
     * @return array
     */
    public function makeSelectTree($depth = Category::CATE_THREE) :array
    {
        $tree = $this->getTree($depth);

        return [[
            'id'=>0,
            'title'=>'顶级分类',
            'children'=>$tree
        ]];
    }

    /**
     * Notes: 返回 封装 [0, pid] 格式
     * Author: Bruce.z
     * DateTime: 2022/2/15 16:14
     * @param $id
     * @return array
     */
    public function getParentID($id) :array
    {
        $re = $this->getOne(['id'=>$id],['id','pid']);
        if($re['pid'] == 0) return [0];

        $return = array_merge([$re['pid']], $this->getParentID($re['pid']));
        sort($return);
        return $return;
    }

    /**
     * Notes: 详情组装
     * Author: Bruce.z
     * DateTime: 2022/6/10 10:19
     * @param int $id
     * @return array
     */
    public function detail(int $id):array
    {
        $detail = $this->getOne(['id'=>$id]);
        $detail['ids'] = $this->getParentID($id);

        return $detail;
    }
}
